package com.shop.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.shop.entity.SocketMsg;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RestController;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

@ServerEndpoint("/websocket/{username}")
@RestController
@Slf4j
public class WebSocketServer {

    //静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;
    //concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。
    private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();
    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;

    private static Map<String, Session> map = new ConcurrentHashMap<>();

    private String username;

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("username") String username) {
        try {
            this.session = session;
            this.username = username;
            map.put(session.getId(), session);
            webSocketSet.add(this);
            addOnlineCount();
            log.info("用户" + username+ "上线了" + ",当前在线人数为" + getOnlineCount());
            sendMessage("连接成功" + ",当前在线人数为" + getOnlineCount());
        }catch (IOException e) {
            log.error("websocket IO异常");
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);
        subOnlineCount();
        log.info("有一连接关闭！当前在线人数为" + getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, @PathParam("username") String username) throws Exception {
        log.info("收到客户端的消息{}" + message);
        ObjectMapper objectMapper = new ObjectMapper();
        SocketMsg socketMsg;
        try {
            if (!StringUtils.isEmpty(message)) {
                socketMsg = objectMapper.readValue(message, SocketMsg.class);
                if(socketMsg.getType() == 1){ //一对一
                    socketMsg.setFromUser(session.getId());
                    //发消息
                    Session fromSession = map.get(socketMsg.getFromUser());
                    //接收消息
                    Session toSession = map.get(socketMsg.getToUser());
                    if(toSession != null){
                        fromSession.getAsyncRemote().sendText(username + ":" + socketMsg.getMsg());
                        toSession.getAsyncRemote().sendText(username + ":" + socketMsg.getMsg());
                    }else{
                        fromSession.getAsyncRemote().sendText("对方已离线");
                    }
                }else{
                    //群发消息
                    for (WebSocketServer item : webSocketSet) {
                        try {
                            item.sendMessage(username + ":" + socketMsg.getMsg());
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }else {
                log.info("消息不能为空");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("连接错误：{}", error.getMessage());
        error.printStackTrace();
    }

    /**
     * 实现服务器主动推送
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    /**
     * 群发自定义消息
     */
    public static void sendInfo(String message, @PathParam("username") String username) throws IOException {
        log.info("推送消息到窗口" + username + "，推送内容:" + message);
        for (WebSocketServer item : webSocketSet) {
            try {
                //这里可以设定只推送给这个sid的，为null则全部推送
                if (username == null) {
                    item.sendMessage(message);
                } else if (item.username.equals(username)) {
                    item.sendMessage(message);
                }
            } catch (IOException e) {
                continue;
            }
        }
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocketServer.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocketServer.onlineCount--;
    }

    public static CopyOnWriteArraySet<WebSocketServer> getWebSocketSet() {
        return webSocketSet;
    }
}

